package com.atguigu.edu2021.mock;

import com.atguigu.edu2021.mock.config.AppConfig;
import com.atguigu.edu2021.mock.factory.ClearService;
import com.atguigu.edu2021.mock.factory.UserStageChain;
import com.atguigu.edu2021.mock.factory.UserStageChainFactory;
import com.atguigu.edu2021.mock.service.TestPaperService;
import com.atguigu.edu2021.mock.service.UserInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Slf4j
public class MockTask {

    @Autowired
    ThreadPoolTaskExecutor poolExecutor;

    @Autowired
    ClearService clearService;

    @Autowired
    UserInfoService userInfoService;

    @Autowired
    TestPaperService testPaperService;

    public void mainTask( ) {


        if( AppConfig.mock_clear_busi.equals("1")){
            System.out.println("---初始化清理业务数据----");
            clearService.clearBusi();
            System.out.println("--- 清理业务数据完成----");
        }

        if( AppConfig.if_init_paper.equals("1")){
            System.out.println("---初始化试卷----");
            testPaperService.initPaper();
            System.out.println("--- 试卷初始化完成----");
        }


        System.out.println("---初始化用户会话，预计初始化："+AppConfig.user_session_count+" 个 ---");

        UserStageChainFactory userStageChainFactory =   UserStageChainFactory.builder().userSessionCount(AppConfig.user_session_count).build();
        List<UserStageChain> userStageChainList = userStageChainFactory.produce();

        System.out.println("---初始化会话路径完成，开始多线程推演："+userStageChainList.size()+"   ---");

        for (UserStageChain userStageChain : userStageChainList) {
            log.debug ("访问流程:"+userStageChain.getVisitStages());
            log.debug ("学习流程:"+userStageChain.getStudyStages() );
            poolExecutor.execute(userStageChain);
            log.debug ("active+" + poolExecutor.getActiveCount());
        }


        while(true){
            try {
                Thread.sleep(1000);
                System.out.println("---演算中...---");
                if(poolExecutor.getActiveCount()==0){
                    System.out.println("---演算完成  ---");
                    poolExecutor.destroy();
                    return;
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }


    }

}
